namespace Crux.Core.Dapper.SqlGenerator;
public partial class SqlGenerator<TEntity>
    where TEntity : class
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="predicate"></param>
    /// <param name="ignoreFilter"></param>
    /// <param name="includes"></param>
    /// <returns></returns>
    public virtual SqlQuery GetAny(
        Expression<Func<TEntity, bool>>? predicate,
        bool ignoreFilter = false,
        params Expression<Func<TEntity, object>>[] includes)
    {
        var sqlQuery = new SqlQuery(this.Provider);

        switch (Provider)
        {
            case SqlProvider.SQLite:
            case SqlProvider.MSSQL:
            case SqlProvider.MySQL:
            case SqlProvider.PostgreSQL:
                sqlQuery.SqlBuilder
                    .AppendLine("SELECT CASE WHEN EXISTS (");
                break;

            case SqlProvider.Oracle:
                sqlQuery.SqlBuilder
                    .AppendLine(@"SELECT CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END
                                  FROM dual
                                  WHERE EXISTS (");
                break;
        }

        sqlQuery.SqlBuilder
            .Append("SELECT 1");

        if (includes.Any())
        {
            var joinsBuilder = AppendJoinToSelect(sqlQuery, true, includes);
            sqlQuery.SqlBuilder
                .Append(" FROM ")
                .Append(TableName)
                .Append(" ");

            sqlQuery.SqlBuilder.Append(joinsBuilder);
        }
        else
        {
            sqlQuery.SqlBuilder
                .Append(" FROM ")
                .Append(TableName)
                .Append(" ");
        }

        AppendWherePredicateQuery(sqlQuery, predicate, QueryType.Select, ignoreFilter);

        switch (this.Provider)
        {
            case SqlProvider.MSSQL:
            case SqlProvider.SQLite:
                sqlQuery.SqlBuilder
                    .AppendLine()
                    .AppendLine(") THEN 1 ELSE 0 END");
                break;

            case SqlProvider.MySQL:
                sqlQuery.SqlBuilder
                    .AppendLine()
                    .AppendLine("LIMIT 1")
                    .AppendLine(") THEN 1 ELSE 0 END");
                break;

            case SqlProvider.PostgreSQL:
                sqlQuery.SqlBuilder
                    .AppendLine()
                    .AppendLine(") THEN TRUE ELSE FALSE END");
                break;

            case SqlProvider.Oracle:
                sqlQuery.SqlBuilder
                    .AppendLine()
                    .AppendLine(")");
                break;
        }

        return sqlQuery;
    }
}